package com.scorpio.common.utils;


import com.scorpio.common.utils.bean.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 转换工具类
 */
public class ConvertUtils {
    private static Logger logger = LoggerFactory.getLogger(ConvertUtils.class);

    public static <T> T sourceToTarget(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
        } catch (Exception e) {
            logger.error("convert error ", e);
        }

        return targetObject;
    }

    public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target) {
        if (sourceList == null) {
            return null;
        }

        List targetList = new ArrayList<>(sourceList.size());
        try {
            for (Object source : sourceList) {
                T targetObject = target.newInstance();
                BeanUtils.copyProperties(source, targetObject);
                targetList.add(targetObject);
            }
        } catch (Exception e) {
            logger.error("convert error ", e);
        }

        return targetList;
    }

    /**
     * 该方法是用于相同对象不同属性值的合并，如果两个相同对象中同一属性都有值，那么sourceBean中的值会覆盖tagetBean重点的值
     *
     * @param sourceBean 被提取的对象bean 参数null则忽略变量
     * @param targetBean 用于合并的对象bean
     * @return targetBean, 合并后的对象
     */
    public static <T> void combineSydwCore(T sourceBean, T targetBean) {
        Class sourceBeanClass = sourceBean.getClass();
        Class targetBeanClass = targetBean.getClass();

        Field[] sourceFields = sourceBeanClass.getDeclaredFields();
        for (int i = 0; i < sourceFields.length; i++) {
            try {

                Field sourceField = sourceFields[i];
                if (Modifier.isStatic(sourceField.getModifiers())) {
                    continue;
                }
                sourceField.setAccessible(true);
                Object value = sourceField.get(sourceBean);
                if (value == null) continue;
                Field targetField = targetBeanClass.getDeclaredField(sourceField.getName());
                if (Modifier.isStatic(sourceField.getModifiers())) {
                    continue;
                }
                targetField.setAccessible(true);
                targetField.set(targetBean, sourceField.get(sourceBean));
            } catch (Exception e) {
            }
        }
    }
}
